<?php

namespace yak\layui\controllers;

use yak\layui\behaviors\AuthFilter;
use yak\layui\behaviors\LayuiCreatorBehavior;
use yak\layui\behaviors\LayuiEditorBehavior;
use yak\layui\behaviors\LayuiExcelDataBehavior;
use yak\layui\behaviors\LayuiSearchBehavior;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Request;
use yii\web\Response;

/**
 * Class BaseController
 * @package yak\layui\controllers
 */
class BaseController extends Controller
{
    /**
     * @var array
     */
    protected $onlyList = ['index'];

    /**
     * @var array
     */
    protected $onlyCreator = ['create'];

    /**
     * @var array
     */
    protected $onlyEditor = ['update'];

    /**
     * @var array
     */
    protected $onlyExcel = ['output'];

    /**
     * @var array
     */
    protected $authExcept = [];

    /**
     * @var array
     */
    protected $closeCsrfValidate = ['upload'];

    /**
     * @var array
     */
    protected $verbs = [
        'delete' => ['POST'],
        'batch-delete' => ['POST'],
    ];

    public function behaviors()
    {
        return [
            'auth' => [
                'class' => AuthFilter::class,
                'except' => $this->authExcept
            ],
            'layui-list' => [
                'class' => LayuiSearchBehavior::class,
                'only' => $this->onlyList
            ],
            'layui-creator' => [
                'class' => LayuiCreatorBehavior::class,
                'only' => $this->onlyCreator
            ],
            'layui-editor' => [
                'class' => LayuiEditorBehavior::class,
                'only' => $this->onlyEditor
            ],
            'layui-excel' => [
                'class' => LayuiExcelDataBehavior::class,
                'only' => $this->onlyExcel
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => $this->verbs
            ]
        ];
    }

    public function beforeAction($action)
    {
        if(in_array($action->id, $this->closeCsrfValidate)) {
            $action->controller->enableCsrfValidation = false;
        }
        return parent::beforeAction($action);
    }

    protected function ajaxHeaderClass($model)
    {
        return get_class($model);
    }

    protected function ajaxSuccess($data = [])
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return ['code' => 0, 'msg' => 'success', 'data' => $data];
    }

    protected function ajaxRedirect($url, $data = [])
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return ['code' => 302, 'msg' => 'success', 'redirect' => $url, 'data' => $data];
    }

    protected function ajaxError($msg = 'error')
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return ['code' => 1, 'msg' => $msg];
    }
}